import { Component, OnInit, OnDestroy } from '@angular/core';
import { _HttpClient } from '@delon/theme';

import { Device, Page, ResultBean, DeviceStatus } from '@shared/bean';
import { format } from '@delon/util';
import { Subscription } from 'rxjs';
import {
  MqttService,
  IMqttMessage,
 } from 'ngx-mqtt';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
})
export class DashboardComponent implements OnInit, OnDestroy {
  topic = '/+/test';
  data: Page = new Page();
  devices: Device[] = [];

  private subscription: Subscription;
  public msg: string;

  constructor(
    private http: _HttpClient,
    private _mqttService: MqttService
  ) {
   // _mqttService.connect({username: 'enbool', password: 'admin123'});
    // console.log('login...');
  }

  ngOnInit() {
    this.http.post('/api/devices/query').subscribe((res: ResultBean<Page>) => {
      this.data = res.data;
      this.devices = this.data.content;
    });
    this.subscription = this._mqttService.observe(this.topic).subscribe((message: IMqttMessage) => {
      const deviceId = message.topic.split('/')[1];
      console.log(deviceId);
      let deviceStatus: DeviceStatus;
      this.msg = message.payload.toString();
      deviceStatus = JSON.parse(this.msg);

      this.devices.forEach(device => {
        if (device.name === deviceStatus.clientid) {
          device.uses = deviceStatus.uses;
          device.isOn = deviceStatus.isOn;
        }
      });
      console.log(this.msg);
    });

  }
  public ngOnDestroy() {
    // this.subscription.unsubscribe();
    // this._mqttService.disconnect();
  }

}
